import {
    Image,
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    TextInput,
    FlatList,
    KeyboardAvoidingView,
    Platform,
    RefreshControl,
    Keyboard,
    Dimensions,
    TouchableWithoutFeedback
} from 'react-native';
import {Stack, useLocalSearchParams, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';
import increateIcon from "@/assets/images/chatIcon/increateIcon.png"
import ChatReaderItem from "@/components/ChatReaderItem/index";
import avator from "@/assets/images/me/avator.png";
import {useEffect, useRef, useState} from "react";
import pirtureIcon from "@/assets/images/chatIcon/pirtureIcon.png"
import { useMessageStore } from "@/hooks/im/message"
import { useRequest, useUpdateEffect } from "ahooks";
import OpenIMSDKRN from "open-im-sdk-rn"
import { v4 as uuidv4 } from "uuid";
import {useSelector} from "react-redux";
import {RootState} from "@/store/rootReducer";
import {useConversationStore} from "@/hooks/im/conversation";
import { useSendMessage } from "@/hooks/im/useSendMessage";
import { useLatest } from "ahooks";
import groupShareBtn from "@/assets/images/chatIcon/groupShareBtn.png"
import groupOutIcon from "@/assets/images/chatIcon/groupOutIcon.png"
import * as ImagePicker from "expo-image-picker";
import {loadingService} from "@/utils/loadingServer";
import {getToken} from "@/utils";
import axios from "axios";
import {api} from "@/config/config-params";
import {showToast} from "@/utils/rootToast";

export default function chatScreen() {

    const messageStore = useMessageStore();

    const getHistoryMessageList = useMessageStore((state) => state.getHistoryMessageListByReq);
    const currentGroupInfo = useConversationStore((state) => state.currentGroupInfo)
    const currentConversation = useConversationStore((state) => state.currentConversation);
    const currentMemberInGroup = useConversationStore((state) => state.currentMemberInGroup);
    const currentGroupList = useConversationStore((state) => state.currentGroupList);
    const getCurrentGroupMenmberInfoByReq = useConversationStore((state) => state.getCurrentGroupMenmberInfoByReq);
    const latestCurrentConversation = useLatest(currentConversation);

    const router = useRouter();
    const chatItemRef = useRef(null);
    const flatListRef = useRef<FlatList<any>>(null);
    const { sendMessage } = useSendMessage();

    const inptRef = useRef(null);
    const [showTool, setShowTool] = useState(false);
    const [message, setMessage] = useState("")
    const [inGroup, setInGroup] = useState(true);

    const { runAsync: initMessages, cancel } = useRequest(getHistoryMessageList, {
        manual: true,
    });

    const login = useSelector((state: RootState) => state.login);

    const routerParms = useLocalSearchParams();

    useEffect(() => {
        console.log('messageStore.historyMessageList', messageStore.historyMessageList);
        //查看用户是否在当前群聊
        // if (currentGroupInfo?.status == 0 && currentConversation?.conversationType == 3) {
        //     console.log('getUsersInGroupParams', {
        //         groupID: currentGroupInfo?.groupID,
        //         userIDList: [login?.userInfo?.uid],
        //     });
        //     OpenIMSDKRN.getUsersInGroup({
        //         groupID: currentGroupInfo?.groupID,
        //         userIDList: [login?.userInfo?.uid],
        //     }, uuidv4())
        //         .then(res => {
        //             console.log('getUsersInGroupgetUsersInGroup', res)
        //         })
        //         .catch(err => {
        //             console.log('err', err);
        //         })
        // };
    }, [])

    useEffect(() => {
        initMessages();

        return () => {
            cancel();
        };
    }, [])


    const checkUnread = () => {
        if (!latestCurrentConversation.current) return;
        if (latestCurrentConversation.current.unreadCount > 0) {
            OpenIMSDKRN.markConversationMessageAsRead(latestCurrentConversation.current.conversationID, uuidv4());
        }
    };


    useEffect(() => {
        checkUnread();
        return () => checkUnread();
    }, []);

    useEffect( () => {
        console.log('currentGroupInfo', currentMemberInGroup);
    }, [currentGroupInfo, currentMemberInGroup])

    const scrollToBottom = () => {
        setTimeout(() => {
            flatListRef.current?.scrollToOffset({ offset: 0, animated: true });
        }, 500);
    };

    useEffect(() => {
        const keyboardDidShowListener = Keyboard.addListener("keyboardDidShow", scrollToBottom);
        return () => {
            keyboardDidShowListener.remove();
        };
    }, []);


    const handleSendMessage = async function () {

        if (!message) return;

        const messages = await OpenIMSDKRN.createTextMessage(message, uuidv4());
        sendMessage({ message: messages });
        setMessage("");
        scrollToBottom();
    };

    const onChangemessage = function (val) {
        setMessage(val)
    };

    const goGroupSetting = function () {
        router.push("/groupSetting")
        getCurrentGroupMenmberInfoByReq(currentGroupInfo?.groupID);
    };

    const openImagePicker = () => {

        const pickImage = async () => {
            // Request media library permissions
            let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();

            if (permissionResult.granted === false) {
                alert('Permission to access the media library is required!');
                return;
            }

            // Open image picker
            let result = await ImagePicker.launchImageLibraryAsync({
                mediaTypes: ImagePicker.MediaTypeOptions.All,
                allowsEditing: true,
                quality: 1,
            });

            if (!result.canceled) {
                uploadAvator(result.assets[0]);
                // setAvatorImg(result.assets[0].uri);
            }
        };

        pickImage();

        // ImagePicker.openPicker({
        //     multiple: false, // 支持多图选择
        //     mediaType: 'photo', // 选择图片类型
        //     maxFiles: 1, // 最多选择9张图片，类似微信的多图选择限制
        //     compressImageQuality: 0.8, // 压缩图片质量
        // })
        //     .then((images) => {
        //         console.log('选择的图片:', images);
        //         // 在这里处理选中的图片数组
        //     })
        //     .catch((error) => {
        //         if (error.code === 'E_PICKER_CANCELLED') {
        //             console.log('用户取消了选择');
        //         } else {
        //             console.log('选择图片时出错: ', error);
        //         }
        //     });
    };

    const uploadAvator = async function (image) {
        if (!image) return;

        console.log('image', image);

        const formData = new FormData();
        formData.append('avatar', {
            uri: image.uri,
            type: image.type, // mime 类型，例如 'image/jpeg'
            name: image.fileName, // 图片名称
        });

        loadingService.show();

        const token = await getToken();

        try {
            const response = await axios.post(`${api}/account/uploadAvatar`, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    "Authorization": token,
                },
            });
            console.log('response', response.data.data);
            if (response?.data.code == 200) {
                // setAvatorImg(response.data.data.url)
                const uri = response.data?.data?.hdUrl;
                const screenWidth = Dimensions.get('window').width;
                const maxImageWidth = screenWidth * 0.4; // 设置图片最大宽度为屏幕宽度的60%
                Image.getSize(uri, async (originalWidth, originalHeight) => {
                    let scaledWidth = originalWidth;
                    let scaledHeight = originalHeight;

                    if (originalWidth > maxImageWidth) {
                        // 如果图片宽度超过最大宽度，则按比例缩放
                        const ratio = maxImageWidth / originalWidth;
                        scaledWidth = Number(maxImageWidth);
                        scaledHeight = Number(originalHeight * ratio);
                    }

                    try {
                        const picBaseInfo = {
                            uuid: uuidv4(),
                            type: image.type,
                            size: 1024,
                            width: Math.floor(scaledWidth),
                            height: Math.floor(scaledHeight),
                            url: uri,
                        };
                        console.log("picBaseInfo", picBaseInfo);

                        const message = await OpenIMSDKRN.createImageMessageByURL({
                            sourcePicture: picBaseInfo,
                            bigPicture: picBaseInfo,
                            snapshotPicture: picBaseInfo,
                            sourcePath: ""
                        }, uuidv4());
                        sendMessage({ message });
                    } catch (e) {
                        console.log('e', e);
                    };
                });
            } else {
                showToast(response?.data.msg)
            };

            loadingService.hide();
        } catch (error) {
            console.error('上传失败：', error);
            loadingService.hide();
        }
    };


    const sendImg = async function () {

        openImagePicker();
        // const uri = "https://web.rentsoft.cn/api_enterprise/object/9711868424/msg_picture_4d4d8c3f12ee29d74d1a97906ed79bec.jpg";
        // const screenWidth = Dimensions.get('window').width;
        // const maxImageWidth = screenWidth * 0.4; // 设置图片最大宽度为屏幕宽度的60%
        // Image.getSize(uri, async (originalWidth, originalHeight) => {
        //     let scaledWidth = originalWidth;
        //     let scaledHeight = originalHeight;
        //
        //     if (originalWidth > maxImageWidth) {
        //         // 如果图片宽度超过最大宽度，则按比例缩放
        //         const ratio = maxImageWidth / originalWidth;
        //         scaledWidth = Number(maxImageWidth);
        //         scaledHeight = Number(originalHeight * ratio);
        //     }
        //
        //     console.log('scaledWidth', scaledWidth);
        //     console.log('scaledHeight', scaledHeight);
        //
        //     try {
        //         const picBaseInfo = {
        //             uuid: uuidv4(),
        //             type: 'jpg',
        //             size: 1024,
        //             width: Math.floor(scaledWidth),
        //             height: Math.floor(scaledHeight),
        //             url: uri,
        //         };
        //
        //         const message = await OpenIMSDKRN.createImageMessageByURL({
        //             sourcePicture: picBaseInfo,
        //             bigPicture: picBaseInfo,
        //             snapshotPicture: picBaseInfo,
        //             sourcePath: ""
        //         }, uuidv4());
        //         console.log('createImageMessageByURL',message)
        //         sendMessage({ message });
        //     } catch (e) {
        //         console.log('e', e);
        //     };
        // });
    };


    return (
        <View style={{ height: "100%", backgroundColor: "#F7F6F8" }}>
            <Stack.Screen
                options={{
                    // title: '未知', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#FFF', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                    headerRight: () => (
                        (currentGroupInfo?.status == 0 && currentConversation?.conversationType == 3) && (
                            <TouchableOpacity onPress={goGroupSetting}>
                                <View style={{ width: 19, height: 19 }}>
                                    <Image source={groupShareBtn} style={{ width: "100%", height: "100%" }} />
                                </View>
                            </TouchableOpacity>
                        )
                    ),
                }}
            />
            <KeyboardAvoidingView
                style={{ flex: 1 }}
                behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
                keyboardVerticalOffset={Platform.OS === 'ios' ? 64 : 0} // 设置 iOS 的偏移量
            >
                <View style={{ flex: 1 }}>
                    <FlatList
                        data={messageStore.historyMessageList}
                        ref={chatItemRef}
                        onEndReached={() => initMessages(true)}
                        renderItem={(item: any) => {
                            return (
                                <TouchableOpacity activeOpacity={1} onPress={() => setShowTool(false)}>
                                    <ChatReaderItem item={item} />
                                </TouchableOpacity>
                            )
                        }}
                        contentContainerStyle={{ flexGrow: 1, justifyContent: 'flex-end' }}
                        // onContentSizeChange={() => {
                        //     if (chatItemRef?.current) {
                        //         chatItemRef.current.scrollToOffset({ animated: false, offset: 0 });
                        //     }
                        // }}
                        inverted
                    />
                </View>


                    <View style={styles.footerContainer}>
                        <View style={{ flexDirection: "row", alignItems: "center" }}>
                            {
                                (currentGroupInfo?.status == 0 || currentConversation?.conversationType == 1)  && (
                                    <>
                                        <View style={styles.textInputWrap}>
                                            <TextInput
                                                style={styles.inpt}
                                                ref={inptRef}
                                                onSubmitEditing={handleSendMessage}  // 监听“Enter”键事件
                                                value={message}
                                                onChangeText={onChangemessage}
                                                returnKeyType="send"  // 设置回车键为 "发送"
                                                onFocus={() => setShowTool(false)}
                                            />
                                        </View>
                                        {/*<TouchableOpacity onPress={handleSendMessage} style={styles.sendBtn}>*/}
                                        {/*    <Text style={styles.sendBtnText}>发送</Text>*/}
                                        {/*</TouchableOpacity>*/}
                                        <TouchableOpacity onPress={() => {
                                            if(!showTool) {
                                                inptRef?.current?.blur();
                                            };
                                            setShowTool(!showTool)

                                        }}>
                                            <View style={styles.increateIcon}>
                                                <Image source={increateIcon} style={{ width: "100%", height: "100%" }} />
                                            </View>
                                        </TouchableOpacity>
                                    </>
                                )
                            }
                            {
                                ((currentGroupInfo?.status == 2 && currentConversation?.conversationType == 3)) && (
                                    <View style={styles.groupOutContainer}>
                                        <View style={styles.groupOutIcon}>
                                           <Image source={groupOutIcon} style={{width: "100%", height: '100%' }}/>
                                        </View>
                                        <Text style={styles.groupOutText}>无法在已退出的群聊群发消息!</Text>
                                    </View>
                                )
                            }
                        </View>
                        {
                            showTool && (
                                <View style={{ paddingTop: 34, paddingBottom: 100 }}>
                                    <TouchableOpacity onPress={sendImg}>
                                        <View style={styles.toolsWrap}>
                                            <View style={styles.pirtureIcon}>
                                                <Image source={pirtureIcon} style={{ width: "100%", height: "100%" }} />
                                            </View>
                                            <View style={{ marginTop: 5 }}>
                                                <Text style={styles.pirtureText}>图片</Text>
                                            </View>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            )
                        }
                    </View>
            </KeyboardAvoidingView>
        </View>

    );
}

const styles = StyleSheet.create({
    footerContainer: {
        paddingBottom: 44,
        backgroundColor: "#fff",
        paddingTop: 8,
        paddingLeft: 12,
        paddingRight: 12,
    },
    increateIcon: {
        width: 26,
        height: 26,
    },
    inpt: {
        width: "100%",
        paddingHorizontal: 12,
    },
    textInputWrap: {
        flex: 1,
        backgroundColor: "#F7F8F9",
        marginRight: 14,
        borderRadius: 6,
        height: 38,
        flexDirection: "row",
        alignItems: "center"
    },
    toolsWrap: {
        width: 60,
    },
    pirtureIcon: {
        width: 60,
        height: 60,
    },
    pirtureText: {
        fontSize: 14,
        color: "#999999",
        textAlign: "center",
    },
    groupOutIcon: {
        width: 14,
        height: 14,
    },
    groupOutContainer: {
        flexDirection: "row",
        justifyContent: "center",
        width: "100%",
        marginTop: 25,
    },
    groupOutText: {
        color: "#9C9EAC",
        fontSize: 12,
    },
    sendBtn: {
        width: 46,
        height: 25,
        backgroundColor: "#EC6138",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",

    },
    sendBtnText: {
        color: "#fff",
        fontSize: 14,
    },
});
